package com.yanqu.road.server.gameplayer.module.chefduel;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.chefduel.ChefDuelData;
import com.yanqu.road.entity.activity.chefduel.ChefDuelFood;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.activity.chefDuel.eChefDuelActivityType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.chefduel.ChefDuelProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.manger.activity.RelationActivityMgr;
import com.yanqu.road.server.manger.activity.chefduel.ChefDuelActivityMgr;
import com.yanqu.road.server.manger.activity.chefduel.ChefDuelMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.pb.ChefDuelPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChefDuelModule extends GeneralModule {

    public ChefDuelModule(GamePlayer player) {
        super(player);
    }

    //活动id 用户数据
    private Map<Integer, ChefDuelData> chefDuelDataMap = new ConcurrentHashMap<>();

    //结算了没有转换道具积分的库里把数据拉出来转换一下
    private Map<Integer,ChefDuelData> cookBoyHistoryDataMap = new ConcurrentHashMap<>();

    //第三阶段的礼包只有有资格参赛的才能买
    public boolean canPrecharge3(int mallId){
        MallInfo mallInfo = RelationActivityMgr.getMallInfo(mallId);
        if(mallInfo == null){
            return false;
        }
        if(!chefDuelDataMap.containsKey(mallInfo.getActivityId())){
            return false;
        }
        if (player.getModule(ActivityMallModule.class).isOverLimitBuyCount(mallInfo, 1)) {
            //限购
            return false;
        }
        if("1".equals(mallInfo.getCanBuyParam())){
            return chefDuelDataMap.get(mallInfo.getActivityId()).isAble();
        }
        return true;
    }

    public boolean canPrecharge2(int mallId){
        MallInfo mallInfo = RelationActivityMgr.getMallInfo(mallId);
        if(mallInfo == null){
            return false;
        }
        if(!chefDuelDataMap.containsKey(mallInfo.getActivityId())){
            return false;
        }
        if (player.getModule(ActivityMallModule.class).isOverLimitBuyCount(mallInfo, 1)) {
            //限购
            return false;
        }
        if("1".equals(mallInfo.getCanBuyParam())){
            return chefDuelDataMap.get(mallInfo.getActivityId()).isAble();
        }
        return true;
    }

    public int syncSelfBanquetTable(int activityId){
        ChefDuelProto.ChefDuel3SelfDataSyncMsg.Builder syncMsg = ChefDuelProto.ChefDuel3SelfDataSyncMsg.newBuilder();
        if(chefDuelDataMap.containsKey(activityId)){
            ChefDuelData cookBoyData = chefDuelDataMap.get(activityId);
            if(cookBoyData.getNo() != eChefDuelActivityType.Phase3.getChildType()){
                return GameErrorCode.E_ACTIVITY_NO_FOUND;
            }
            syncMsg = ChefDuelPb.parseSelfBanquetTableSync(cookBoyData);
//            player.sendPacket(Protocol.U_CHEF_DUEL3_DATA_SYNC, syncMsg);
            player.sendPacket(Protocol.C_CHEF_DUEL3_DATA_SYNC, syncMsg);
            return 0;
        }
        return GameErrorCode.E_ACTIVITY_NO_FOUND;
    }


    /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓小当家2↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
    public int syncSelfDishTable(int activityId,String reward){
        ChefDuelProto.ChefDuel2SelfDishSyncMsg.Builder syncMsg;
        if(chefDuelDataMap.containsKey(activityId)){
            ChefDuelData cookBoyData = chefDuelDataMap.get(activityId);
            if(cookBoyData.getNo() != eChefDuelActivityType.Phase2.getChildType()){
                return GameErrorCode.E_ACTIVITY_NO_FOUND;
            }
            syncMsg = ChefDuelPb.parseSelfDishTableSync(cookBoyData);
            syncMsg.setReward(reward);
            player.sendPacket(Protocol.U_CHEF_DUEL2_SYNC_DISH_TABLE, syncMsg);
            return 0;
        }
        return GameErrorCode.E_ACTIVITY_NO_FOUND;
    }


    public boolean isAble(int activityId){
        if(!chefDuelDataMap.containsKey(activityId)){
            return false;
        }
        return chefDuelDataMap.get(activityId).isAble();
    }

    //获取自己的挑菜状态等信息
    public int getSelfDish(int activityId){
        ChefDuelProto.ChefDuel2SelfDishRespMsg.Builder syncMsg;
        if(chefDuelDataMap.containsKey(activityId)){
            ChefDuelData cookBoyData = chefDuelDataMap.get(activityId);
            if(cookBoyData.getNo() != eChefDuelActivityType.Phase2.getChildType()){
                return GameErrorCode.E_ACTIVITY_NO_FOUND;
            }
            syncMsg = ChefDuelPb.parseSelfDishTableMsg(cookBoyData);
            player.sendPacket(Protocol.U_CHEF_DUEL2_GET_DISH_TABLE, syncMsg);
            return 0;
        }
        return GameErrorCode.E_ACTIVITY_NO_FOUND;
    }


    public void initChefDuelSystem() {
        loginSendMsg();
    }

    //设置一次每个活动都不重置，禁用的试吃汤勺
    public List<Integer> getForbidSpoonIdList(int activityId){
        List<Integer> forbidSpoonIdList = new ArrayList<>();
        List<Integer> spoonIdList = ChefDuelActivityMgr.getChefDuel2SpoonIdList(activityId);
        long value = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.ChefDuel2ForbidSpoon);
        for(int i = 0; i < spoonIdList.size() ; i++){
            //判断一下对应的那位是不是1
            if(((value & (1<<i))>>i) == 1){
                forbidSpoonIdList.add(spoonIdList.get(i));
            }
        }
        return forbidSpoonIdList;
    }

    //每次设置保存一下在用户身上先
    public void setForbidSpoonIdList(int activityId,List<Integer> forbidSpoonIdList){
        List<Integer> spoonIdList = ChefDuelActivityMgr.getChefDuel2SpoonIdList(activityId);
        for(Integer forbidSpoonId : forbidSpoonIdList){
            if(!spoonIdList.contains(forbidSpoonId)){
                return;
            }
        }
        long value = 0;
        for(Integer forbidSpoonId : forbidSpoonIdList){
            int index = spoonIdList.indexOf(forbidSpoonId);
            value = value | (1<<index);
        }
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.ChefDuel2ForbidSpoon,value);
    }

    public void checkChefDuel2Joiner(){
        List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(), eChefDuelActivityType.Phase2.getChildType());
        if(activityInfoList.size() > 0){
            for(ActivityInfo activityInfo : activityInfoList){
                ChefDuelData cookBoyData = chefDuelDataMap.get(activityInfo.getActivityId());
                if(cookBoyData != null && cookBoyData.getNo() == eChefDuelActivityType.Phase2.getChildType() && cookBoyData.isAble()){
                    ChefDuelProto.CrossChefDuel2CookerJoinSyncMsg.Builder reqMsg = ChefDuelProto.CrossChefDuel2CookerJoinSyncMsg.newBuilder();
                    reqMsg.setActivityId(activityInfo.getActivityId());
                    ChefDuelProto.CrossChefDuelWindUpCookerTempMsg.Builder userMsg = ChefDuelProto.CrossChefDuelWindUpCookerTempMsg.newBuilder();
                    userMsg.setUserId(player.getUserId());
                    userMsg.setScore(0);//不知道哪个前面的活动晋级的
                    userMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
                    reqMsg.addUserInfoList(userMsg);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_CHEF_DUEL2_COOKER_JOIN, reqMsg);
                    GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
                }
            }
        }
    }

    public void checkChefDuel3Joiner(){
        List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(),eChefDuelActivityType.Phase3.getChildType());
        if(activityInfoList.size() > 0){
            for(ActivityInfo activityInfo : activityInfoList){
                ChefDuelData cookBoyData = chefDuelDataMap.get(activityInfo.getActivityId());
                if(cookBoyData != null && cookBoyData.getNo() == eChefDuelActivityType.Phase3.getChildType() && cookBoyData.isAble()){
                    ChefDuelProto.CrossChefDuel3CookerJoinSyncMsg.Builder reqMsg = ChefDuelProto.CrossChefDuel3CookerJoinSyncMsg.newBuilder();
                    reqMsg.setActivityId(activityInfo.getActivityId());
                    ChefDuelProto.CrossChefDuelWindUpCookerTempMsg.Builder userMsg = ChefDuelProto.CrossChefDuelWindUpCookerTempMsg.newBuilder();
                    userMsg.setUserId(player.getUserId());
                    userMsg.setRank(cookBoyData.getPreRank());
                    userMsg.setScore(0);//不知道哪个前面的活动晋级的
                    userMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
                    reqMsg.addUserInfoList(userMsg);
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_CHEF_DUEL3_COOKER_JOIN, reqMsg);
                    GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
                }
            }
        }
    }

    @Override
    public void loginSendMsg() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.ChefDuelPhase2.getValue())) {
            List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(),eChefDuelActivityType.Phase2.getChildType());
            if(activityInfoList.size() > 0){
                for(ActivityInfo activityInfo : activityInfoList){
                    syncSelfDishTable(activityInfo.getActivityId(),"");
                }
            }
        }
        if(SystemOpenMgr.systemOpen(player, eSystemId.ChefDuelPhase3.getValue())) {
            List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(),eChefDuelActivityType.Phase3.getChildType());
            if(activityInfoList.size() > 0){
                for(ActivityInfo activityInfo : activityInfoList){
                    syncSelfBanquetTable(activityInfo.getActivityId());
                }
            }
        }
        checkChefDuel2Joiner();
        checkChefDuel3Joiner();
        sendLoginSync();


        //设置汤勺的
        if(SystemOpenMgr.systemOpen(player, eSystemId.ChefDuelPhase2.getValue())) {
            List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(), eChefDuelActivityType.Phase2.getChildType());
            if(activityInfoList.size() > 0){
                for(ActivityInfo activityInfo : activityInfoList){
                    //每次登陆都去设置一下
                    sendForbidSpoonIdSet(activityInfo.getActivityId());
                }
            }
        }
        List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(),eChefDuelActivityType.Phase1.getChildType());
        for(ActivityInfo activityInfo : activityInfoList){
            int activityId = activityInfo.getActivityId();
            //同步一下最新的区服排行数据，可能没变化
//            BigInteger value = RelationActivityMgr.getUserActivityConditionValue(activityId, eGamePlayerEventType.ChefDuel1IntegralServerCrossRank.getValue());
//            RelationActivityMgr.conditionNotify(activityId,player.getUserId(), eGamePlayerEventType.ChefDuel1IntegralServerCrossRank.getValue(),
//                    new RelationActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, value,"", activityId));
        }

    }

    public void sendForbidSpoonIdSet(int activityId){
        List<Integer> spoonIdList = getForbidSpoonIdList(activityId);
        ChefDuelMgr.sendForbidSpoon(activityId,player.getUserId(),spoonIdList);
    }

    public void sendLoginSync(){
        List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue(),eChefDuelActivityType.Phase3.getChildType());
        if(activityInfoList.size() > 0){
            for(ActivityInfo activityInfo : activityInfoList){
                ChefDuelData cookBoyData = chefDuelDataMap.get(activityInfo.getActivityId());
                if(cookBoyData != null && cookBoyData.getNo() == eChefDuelActivityType.Phase3.getChildType()){
                    ChefDuelProto.CrossChefDuel3LoginSyncMsg.Builder reqMsg = ChefDuelProto.CrossChefDuel3LoginSyncMsg.newBuilder();
                    reqMsg.setActivityId(activityInfo.getActivityId());
                    reqMsg.setUserId(player.getUserId());
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_CHEF_DUEL3_USER_LOGIN, reqMsg);
                    GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
                }
            }
        }
    }

    //策划要测试做10000道各种菜多少分
    public void test(){

    }


    private Map<Integer, ChefDuelFood> initChefDuelFood(){
        Map<Integer,ChefDuelFood> cookBoyFoodMap = new ConcurrentHashMap<>();
        for(int i = 1; i <= GameConfig.CHEF_DUEL_TABLE_MAX_POSITION; i++){
            ChefDuelFood temp = new ChefDuelFood();
            temp.setPos(i);
            temp.setLevel(0);
            temp.setFraction(0);
            temp.setProcess("");
            cookBoyFoodMap.put(temp.getPos(),temp);
        }
        return cookBoyFoodMap;
    }

    private void setOneFood(Map<Integer,ChefDuelFood> foodTable,ChefDuelFood cookBoyFood){
        for(ChefDuelFood temp : foodTable.values()){
            if(temp.getLevel() == 0){
                temp.setLevel(cookBoyFood.getLevel());
                temp.setFraction(cookBoyFood.getFraction());
                temp.setProcess(cookBoyFood.getProcess());
                break;
            }
        }
    }


    @Override
    public boolean loadData() {
//        test();
        List<ActivityInfo> activityInfoList = ChefDuelActivityMgr.getOpenActivityInfoList(eActivityType.ChefDuel.getValue());
        if(activityInfoList.size() > 0){
            for(ActivityInfo activityInfo : activityInfoList){
                ChefDuelData cookBoyData = null;
                if(activityInfo.getChildType() == eChefDuelActivityType.Phase1.getChildType()){
//                    cookBoyData = ChefDuelMgr.getUserChefDuelData(activityInfo.getActivityId(),player);
                }else if(activityInfo.getChildType() == eChefDuelActivityType.Phase2.getChildType()){
                    cookBoyData = ChefDuelMgr.getUserChefDuel2DataNoLock(activityInfo.getActivityId(),player);
                }else if(activityInfo.getChildType() == eChefDuelActivityType.Phase3.getChildType()){
                    cookBoyData = ChefDuelMgr.getUserChefDuel3Data(activityInfo.getActivityId(),player);
                }
                if(cookBoyData != null){
                    chefDuelDataMap.put(activityInfo.getActivityId(),cookBoyData);
                }
            }
        }
        List<Integer> activityIdList = new ArrayList<>();
        for(ActivityInfo activityInfo : activityInfoList){
            activityIdList.add(activityInfo.getActivityId());
        }
        //回收道具，已经改成只有领奖期才回收了，后面先留着万一要改
        /*cookBoyHistoryDataMap = UserChefDuelBussiness.getUserHistoryRecoverChefDuel2Map(getUserId(),activityIdList);
        for(ChefDuelData cookBoyData : cookBoyHistoryDataMap.values()){
            int integralItemId = ChefDuelActivityMgr.getChefDuel2IntegralItemId(cookBoyData.getActivityId());
            String reward = integralItemId + "=" + cookBoyData.getIntegral();
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.ChefDuel,eLogMoneyType.CrossChefDuel2ActivityHistoryReward);
            cookBoyData.setIntegral(0);
        }
        if(cookBoyHistoryDataMap.size() > 0){
            List<ChefDuelData> updateList = new ArrayList<>(cookBoyHistoryDataMap.values());
            UserChefDuelBussiness.updateUserChefDuelList(updateList);
        }*/
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        return true;
    }

    public int selectCampId(int activityId, int campId) {
        ChefDuelData cookBoyData = chefDuelDataMap.get(activityId);
        if(cookBoyData == null){
            return GameErrorCode.E_CHEF_DUEL2_USER_NOT_ABLE;
        }
        player.sendPacket(Protocol.C_CROSS_CHEF_DUEL2_SELECT_CAMP, ChefDuelProto.ChefDuel2CampSelectReqMsg.newBuilder().setActivityId(activityId).setCampId(campId));
        return 0;
    }

    public boolean hasCamp(int activityId) {
        ChefDuelData cookBoyData = chefDuelDataMap.get(activityId);
        if(cookBoyData == null || cookBoyData.getCampId() <= 0){
            return false;
        }
        return true;
    }

    public Map<Integer, ChefDuelData> getChefDuelDataMap() {
        return chefDuelDataMap;
    }
}
